package com.hxzy.shop.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.shop.common.redis.RedisService;
import com.hxzy.shop.constant.RedisConstant;
import com.hxzy.shop.entity.YxtConfig;
import com.hxzy.shop.entity.YxtCustomer;
import com.hxzy.shop.mapper.YxtConfigMapper;
import com.hxzy.shop.mapper.YxtCustomerMapper;
import com.hxzy.shop.service.YxtCustomerService;
import com.hxzy.shop.utils.WeixinYxtUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能描述: 营销通客服表(YxtCustomer)
 *
 * @author tonneyyy
 */
@Log4j2
@Service
public class YxtCustomerServiceImpl extends ServiceImpl<YxtCustomerMapper, YxtCustomer> implements YxtCustomerService{

    @Autowired
    private RestTemplate restTemplate;
    /**
     * 企业级微信营销通配置
     */
    @Autowired
    private YxtConfigMapper yxtConfigMapper;

    /**
     * 企业级微信营销通微信客服
     */
    @Autowired
    private YxtCustomerMapper yxtCustomerMapper;

    @Autowired
    private RedisService redisService;

    /**
     * 微信营销客服列表
     * @return
     */
    @Override
    public List<YxtCustomer> getTenantRedirectUrl() {
        List<YxtCustomer> customers = new ArrayList<>();
        String accessToken = getAccessToken();
        YxtConfig yxtConfig = yxtConfigMapper.selectOne(null);
        if (ObjectUtil.isNotEmpty(accessToken)) {
            Map<?, ?> kh = restTemplate.getForObject("https://yzt.tencent.com/openapi/kf/account/list?access_token=" + accessToken + "&agency_id=" + yxtConfig.getAgencyId(), HashMap.class);
            log.info("kh:" + kh);
            if ("0".equals(kh.get("errcode").toString())) {
                List<Map<String, Object>> list = (List<Map<String, Object>>) kh.get("account_list");
                for (Map<String, Object> yxtCustomer : list) {
                    Map<?, ?> kfUrl = restTemplate.getForObject("https://yzt.tencent.com/openapi/kf/contact_way?access_token=" + accessToken + "&open_kfid=" + yxtCustomer.get("open_kfid"), HashMap.class);
                    log.info("kfUrl:" + kfUrl);
                    YxtCustomer customer = new YxtCustomer();
                    customer.setOpenKfid(yxtCustomer.get("open_kfid").toString());
                    customer.setName(yxtCustomer.get("name").toString());
                    customer.setServicerNum(Integer.parseInt(yxtCustomer.get("servicer_num").toString()));
                    //获取详情
                    customer.setUrl(kfUrl.get("url").toString());
                    customer.setCorpId(String.valueOf(kfUrl.get("corpid")));
                    customers.add(customer);
                }
                if (customers.size() > 0 && ObjectUtil.isNotEmpty(customers.get(0).getCorpId())) {
                    yxtConfig.setCorpId(customers.get(0).getCorpId());
                    yxtConfigMapper.updateById(yxtConfig);
                }
            }
        }
        return customers;

    }

    /**
     * 获取营销通临时令牌access_token
     * @return
     */
    @Override
    public String getAccessToken() {
        YxtConfig yxtConfig = yxtConfigMapper.selectOne(null);
        if (ObjectUtil.isNull(yxtConfig)) {
            return null;
        }
        //拿到redis当前商店的微信客服列表的令牌
        String key = RedisConstant.YXT_TOKEN + yxtConfig.getId() + yxtConfig.getSecret() + yxtConfig.getMerchantId();
        String token = redisService.getToken(key);
        //如果没有，就要从微信那边获取
        if (ObjectUtil.isEmpty(token)) {
            Map<String, String> prams = new HashMap<>();
            prams.put("id", yxtConfig.getId());
            prams.put("secret", yxtConfig.getSecret());
            //获取企业token
            Map<?, ?> corpToken = restTemplate.postForObject("https://yzt.tencent.com/openapi/gettoken", WeixinYxtUtil.getHttpEntity(prams), HashMap.class);
            if ("0".equals(corpToken.get("errcode").toString())) {
                redisService.saveToken(key, corpToken.get("access_token").toString(), Integer.parseInt(corpToken.get("expires_in").toString()));
                return corpToken.get("access_token").toString();
            }
        }
        log.info("token:" + token);
        return token;
    }
}
